package org.zhadoop.stream.cql.api;

import java.lang.reflect.Field;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zhadoop.stream.api.ConfigAnnotation;
import org.zhadoop.stream.cql.CQLUtils;
import org.zhadoop.stream.cql.exception.SemanticAnalyzerException;
import org.zhadoop.streaming.exception.ErrorCode;

import com.google.common.collect.Maps;

/**
 * 申明属性处理的一些公共方法
 * @author zwd
 *
 */
public class AnnotationUtils {
	private static final Logger LOG = LoggerFactory.getLogger(AnnotationUtils.class);
	
	/**
	 * 获取API 类中的fields和streamingConf的映射关系
	 * @param clazz
	 * @return
	 * @throws SemanticAnalyzerException
	 */
	public static Map<String,String> getConfigMapping(String clazz) throws SemanticAnalyzerException{
		Map<String,String> mapping = Maps.newHashMap();
		Class<?> apiClass = getClass(clazz);
		Field[] fs =apiClass.getDeclaredFields();
		for(Field f: fs){
			ConfigAnnotation annotation = f.getAnnotation(ConfigAnnotation.class);
			if(annotation == null){
				continue;
			}
			String value = annotation.value();
			if(value == null){
				continue;
			}
			
			String key = f.getName();
			mapping.put(key, value);
		}
		return mapping;
	}

	/**
	 * 获取李哥类
	 * @param clazz
	 * @return
	 */
	private static Class<?> getClass(String clazz) throws SemanticAnalyzerException{
		try {
			return Class.forName(clazz,true,CQLUtils.getClassLoader());
		} catch (ClassNotFoundException e) {
			SemanticAnalyzerException exception =
						new SemanticAnalyzerException(e, ErrorCode.SEMANTICANALYZE_UNKOWN_CLASS,clazz);
			LOG.error("Can't find class",exception);
			throw exception;
		}
	}
}
